from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv

from urllib import parse
from .const import DOMAIN, VERSION

CONFIG_SCHEMA = cv.deprecated(DOMAIN)

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    require_admin = entry.options.get('require_admin', False)
    url = entry.data.get('url', '').strip('/')
    hass.http.register_static_path("/ha_novel_www", hass.config.path("custom_components/" + DOMAIN + "/www"), False)
    hass.components.frontend.async_register_built_in_panel(
                        "iframe",
                        "小说阅读器",
                        "mdi:book-open-variant",
                        DOMAIN,
                        { "url": f"/ha_novel_www/index.html?api={parse.quote(url)}&v={VERSION}" },
                        require_admin=require_admin)
    
    entry.async_on_unload(entry.add_update_listener(update_listener))
    return True

async def update_listener(hass, entry):
    """Handle options update."""
    await async_unload_entry(hass, entry)
    await async_setup_entry(hass, entry)

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    hass.components.frontend.async_remove_panel(DOMAIN)
    return True